package com.boarsoft.boar.gateway.weixin.common;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.wechat.entity.WeChatDictionary;

public class WxFormatData {
	
	protected static Logger log = LoggerFactory.getLogger(WxFormatData.class);
	
	public static Map<String, List<WeChatDictionary>> dictionaryMap;

	/**
	 * 格式字符串
	 * 
	 * @param ruleKey
	 *            字典名称
	 * @param ruleCode
	 *            01  保留最后四位     
	 *            02 000018235.00  金额格式化 18,235.00
	 *            03 yyyyMMdd 日期格式 yyyy-MM-dd 
	 *               yyyyMMddHHmmss 日期日期格式  yyyy-MM-dd HH:mm:ss 
	 *               HHmmss 时间格式 HH:mm:ss 
	 *               HHmm 时间格式 HH:mm
	 *            04  数据字典转换 直接映射
	 *            05 表达式
	 * @param data
	 *            消息数据
	 * @return
	 */
	public static String formatData(String ruleKey, String ruleCode, Map<String, Object> msgData) {
		if ("01".equals(ruleCode)) {
			return formatEnd4((String)msgData.get(ruleKey));
		} else if ("02".equals(ruleCode)) {
			return formatMoney((String)msgData.get(ruleKey));
		} else if ("03".equals(ruleCode)) {
			return formatDateStr(msgData, ruleKey);
		} else if ("04".equals(ruleCode)) {
			return formatDictionary((String)msgData.get(ruleKey), ruleKey);
		} else if ("05".equals(ruleCode)) {
			return formatDataJs(msgData, ruleKey);
		}  else {
			return (String)msgData.get(ruleKey);
		}
	}

	/**
	 * 表达式格式化
	 * 
	 * @param msgData 消息数据
	 * @param dictionaryName 
	 * @return
	 */
	private static String formatDataJs(Map<String, Object> msgData, String dictionaryName) {
		try {
			//替换表达式中的数据
			List<WeChatDictionary> list = dictionaryMap.get(dictionaryName);
			WeChatDictionary dictionary = list.get(0);
			String js = dictionary.getDataValue();
			String[] dataKeys = dictionary.getDataKey().split("\\|\\|");
			for (String dataKey : dataKeys) {
				if(null != msgData.get(dataKey)){
					js = js.replaceAll(dataKey, (String)msgData.get(dataKey));
				}else{
					js = js.replaceAll(dataKey, "");
				}
			}
			
			//解析表达式
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("js");
			Object result = engine.eval(js);
			if(result instanceof String){
				return (String)result;
			}else{
				return result.toString();
			}
		} catch (ScriptException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 保留最后四位 
	 * 
	 * @param data
	 * @return
	 */
	public static String formatEnd4(String data) {
		if (data == null || data.length() < 5) {
			return data;
		}
		return data.substring((data.length() - 4), data.length());
	}
	
	/**
	 * 将字符串日期格式化 如： yyyyMMdd 日期格式 yyyy-MM-dd 
	 * @param msgData 消息数据
	 * @param dictionaryName
	 * @return
	 */
	public static String formatDateStr(Map<String, Object> msgData, String dictionaryName) {
		String data = "";
		try{
			List<WeChatDictionary> list = dictionaryMap.get(dictionaryName);
			WeChatDictionary dictionary = list.get(0);
			data = (String)msgData.get(dictionary.getDataKey());
			String[] rules = dictionary.getDataValue().split("\\|\\|");
			SimpleDateFormat df1 = new SimpleDateFormat(rules[0]);
			SimpleDateFormat df2 = new SimpleDateFormat(rules[1]);
			Date date = df1.parse(data);
			return df2.format(date);
		}catch(Exception e){
			log.error("数据转换异常：", e);
		}
		return data;
	}
	
	/**
	 * 将数据转换为对应的值 
	 * @param data
	 * @param dictionaryName
	 * @return
	 */
	public static String formatDictionary(String data, String dictionaryName) {
		try{
			List<WeChatDictionary> list = dictionaryMap.get(dictionaryName);
			for (WeChatDictionary dictionary : list) {
				if(data.equals(dictionary.getDataKey())){
					return dictionary.getDataValue();
				}
			}
		}catch(Exception e){
			log.error("数据转换异常：", e);
		}
		return data;
	}

	/**
	 * 格式化金额
	 * 
	 * @param data
	 * @return
	 */
	public static String formatMoney(String data) {
		if(data == null){
			return data;
		}
		try{
			Double money = Double.parseDouble(data);
			NumberFormat nf = new DecimalFormat("#,###,###,##0.00");
			return nf.format(money);
		}catch(Exception e){
			log.error("数据转化异常：", e);
			return data;
		}
	}
	
	
	public static void main(String[] args){
		
		//替换表达式中的数据
		/*Map<String, Object> msgData = new HashMap<String, Object>();
		msgData.put("OPTYPE", "0");
		msgData.put("TRANTYPE", "2");
		String js = "(OPTYPE==1||OPTYPE==2)?'':(TRANTYPE==2?'（收入）':'（支出）')";
		String[] dataKeys = "OPTYPE|TRANTYPE".split("\\|");
		for (String dataKey : dataKeys) {
			if(null != msgData.get(dataKey)){
				js = js.replaceAll(dataKey, (String)msgData.get(dataKey));
			}else{
				js = js.replaceAll(dataKey, "");
			}
		}
		
		//解析表达式
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		Object result;
		try {
			result = engine.eval(js);
			System.out.println((String)result);
		} catch (ScriptException e) {
			e.printStackTrace();
		}*/
		
/*//		SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
//		SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat df1 = new SimpleDateFormat("HHmmss");
		SimpleDateFormat df2 = new SimpleDateFormat("HH:mm");
		Date date;
		try {
			date = df1.parse("232221");
			System.out.println(df2.format(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}
		
}
